import React, { useEffect, useState } from 'react';
import { View, Text, Image, TouchableOpacity, StyleSheet, Dimensions } from 'react-native';
import TypeWriter from './TypeWriter';
import { useAIStore } from '../store/ai';

const { width, height } = Dimensions.get('window');

interface IntroStep {
  audioFile: number;
  duration: number;
  text?: string;
  images?: Array<{
    time: number;
    source: number;
  }>;
}

const introSteps: IntroStep[] = [
  {
    audioFile: require('../../assets/audio/self_intro.mp3'),
    duration: 15,
    text: '你好，我是万小户，万户积分联盟 AI 语音助手。\n\n我能语音助您绑定积分账户，查明细、推好物、答疑问，\n\n您语音问询或下令，我即响应执行，伴您畅享积分权益。'
  },
  {
    audioFile: require('../../assets/audio/union_intro.mp3'),
    duration: 37,
    images: [
      { time: 0, source: require('../../assets/images/intro1.jpg') },
      { time: 5, source: require('../../assets/images/intro2.jpg') },
      { time: 21, source: require('../../assets/images/intro4.jpg') },
      { time: 32, source: require('../../assets/images/intro6.jpg') }
    ]
  }
];

export const IntroductionGuide = ({ onComplete }: { onComplete: () => void }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [currentImage, setCurrentImage] = useState<number | null>(null);
  const [showEnterButton, setShowEnterButton] = useState(false); // 新增状态，控制“进入”按钮的显示
  const { playAudio: playAudio, stopAudio } = useAIStore();

  useEffect(() => {
    const step = introSteps[currentStep];
    if (!step) return;

    playAudio(step.audioFile);

    setCurrentImage(0);
    setShowEnterButton(false); // 重置“进入”按钮状态

    let imageTimeouts: NodeJS.Timeout[] = [];
    if (step.images) {
      step.images.forEach((image, index) => {
        const timeout = setTimeout(() => {
          setCurrentImage(index);
          if (index === step.images.length - 1) {
            setShowEnterButton(true); // 当显示第六张图片时，显示“进入”按钮
          }
        }, image.time * 1000);
        imageTimeouts.push(timeout);
      });
    }

    const stepTimeout = setTimeout(() => {
      if (currentStep < introSteps.length - 1) {
        setCurrentStep(prev => prev + 1);
      }
    }, step.duration * 1000);

    return () => {
      clearTimeout(stepTimeout);
      imageTimeouts.forEach(timeout => clearTimeout(timeout));
      stopAudio();
    };
  }, [currentStep]);

  const step = introSteps[currentStep];

  const handleSkip = () => {
    stopAudio();
    onComplete();
  };

  const handleEnter = () => {
    stopAudio();
    onComplete();
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={[styles.skipButton, { width: 80, height: 40, alignItems: 'center', justifyContent: 'center'}]} onPress={handleSkip}>
        <Text style={styles.skipText}>跳过</Text>
      </TouchableOpacity>

      <View style={styles.content}>
        {step.text && (
          <TypeWriter
            text={step.text}
            duration={step.duration * 1000}
          />
        )}

        {step.images && currentImage !== null && (
          <Image
            source={step.images[currentImage].source}
            style={styles.image}
            resizeMode="cover"
          />
        )}

        {/* “进入”按钮 */}
        {showEnterButton && (
          <TouchableOpacity style={[styles.enterButton, { borderRadius: 15 }]} onPress={handleEnter}>
            <Text style={styles.enterButtonText}>进入集分宝</Text>
          </TouchableOpacity>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 10,
  },
  skipButton: {
    position: 'absolute',
    top: 40,
    right: 10,
    zIndex: 11,
  },
  skipText: {
    fontSize: 16,
    color: '#666',
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'transparent',
    width: undefined,
    height: undefined,
  },
  content: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: width * 0.05,
  },
  enterButton: {
    position: 'absolute',
    backgroundColor: '#fff', // 白色背景
    paddingHorizontal: 80, // 增大按钮尺寸
    paddingVertical: 25, // 增大按钮尺寸
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 5, // 增加阴影效果
  },
  enterButtonText: {
    fontSize: 20, // 增大文字尺寸
    color: '#000', // 黑色文字
    fontWeight: 'bold', // 加粗文字
  },
});